package com.yuanluludev.pgy

import android.Manifest.permission
import android.app.Activity
import android.app.Application
import android.content.Context
import androidx.annotation.RequiresPermission
import com.pgyer.pgyersdk.PgyerSDKManager
import com.pgyer.pgyersdk.callback.CheckoutCallBack
import com.pgyer.pgyersdk.model.CheckSoftModel
import com.yuanluludev.lib_base.base.BaseActivity
import com.yuanluludev.lib_base.ext.toastFailedMiddle
import com.yuanluludev.lib_utils.util.ActivityUtils
import com.yuanluludev.lib_utils.util.LogUtils
import com.yuanluludev.lib_xpopup.CommonDialogUtils
import com.yuanluludev.pgy.update.PgyUpdateDialog

/**
 * yuanLulu
 * 蒲公英bug监控以及应用升级
 */
object Pgy {

    /**
     * 初始化(建议在application里面初始化)
     */
    fun init(application: Application) {
        PgyerSDKManager
            .Init()
            .setContext(application)
            .start()
    }

    /**
     * 手动检查更新 默认不显示提示
     */
    fun checkVersionUpdate(
        context: Activity,
        isShowTipDialog: Boolean = false,
        isBackgroundDownload: Boolean = false,
        showLoading: (() -> Unit)? = null,
        hideLoading: (() -> Unit)? = null
    ) {

        showLoading?.invoke()
        PgyerSDKManager.checkVersionUpdate(context, object : CheckoutCallBack {
            override fun onNewVersionExist(model: CheckSoftModel) {
                //检查版本成功（有新版本）
                LogUtils.dTag("pgy", "================= ${model.toString()}")
                hideLoading?.invoke()
                showNewVersionDialog(context, model, isBackgroundDownload)
            }

            override fun onNonentityVersionExist(error: String) {
                hideLoading?.invoke()
                //无新版本
                if (isShowTipDialog) showNoNewVersionDialog(context)
            }

            @RequiresPermission(permission.INTERNET)
            override fun onFail(error: String) {
                hideLoading?.invoke()
                //请求异常
                if (isShowTipDialog) "检查更新失败，请稍候重试".toastFailedMiddle()
            }
        })
    }

    /**
     * 显示新版本的弹窗
     */
    private fun showNewVersionDialog(
        context: Context,
        model: CheckSoftModel,
        isBackgroundDownload: Boolean
    ) {
        if (ActivityUtils.isActivityAlive(context)) {
            PgyUpdateDialog
                .newInstance(model, isBackgroundDownload)
                .show(
                    (context as BaseActivity?)?.supportFragmentManager,
                    isCancelable = false
                )
        }
    }

    /**
     * 显示无新版本的弹窗
     */
    private fun showNoNewVersionDialog(context: Context) {
        if (ActivityUtils.isActivityAlive(context)) {
            CommonDialogUtils.showConfirmDialog(
                context = context,
                content = "当前已是最新版本",
                isHideCancel = true
            )
        }
    }

}